#include "clientwidget.h"
#include "ui_clientwidget.h"
#include <QTcpServer>   //监听套接字
#include <QTcpSocket>   //通信套接字
#include <QHostAddress>
#include <QByteArray>
ClientWidget::ClientWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ClientWidget)
{
    ui->setupUi(this);
    setWindowTitle("Client");
    tcpSocket = nullptr;

    //分配空间指定父对象
    tcpSocket = new QTcpSocket(this);
    connect(tcpSocket, &QTcpSocket::connected,[=](){
        ui->textRead->setText("和服务器建立连接成功");
    });
    connect(tcpSocket, &QTcpSocket::readyRead,[=](){
        //获取对方发送的内容
        QByteArray array = tcpSocket->readAll();
        //追加到编辑区中
        ui->textRead->append(array);
    });
    connect(tcpSocket, &QTcpSocket::disconnected,[=](){
        ui->textRead->setText("连接断开");
    });
}

ClientWidget::~ClientWidget()
{
    delete ui;
}

void ClientWidget::on_buttonSend_clicked()
{
    //获取编辑框内容
    if (tcpSocket != nullptr) {
        QString str = ui->textWrite->toPlainText();
        //发送数据
        tcpSocket->write(str.toUtf8().data());
    }
}

void ClientWidget::on_buttonClose_clicked()
{
    //主动和对方断开连接
    if (tcpSocket != nullptr) {
        ui->textRead->setText("连接断开");
        tcpSocket->disconnectFromHost();
        tcpSocket->close();
        tcpSocket = nullptr;
    }
}

void ClientWidget::on_buttonBindOwnPort_clicked()
{
   quint16 portSer = static_cast<quint16>(ui->lineEditPort->text().toInt());
    QString ipSer = ui->lineEditIP->text();
    //主动和服务器建立连接
    tcpSocket->connectToHost(QHostAddress(ipSer),portSer);

}
